const photoZoomout = [
    0.7,
    0.4,
    0.3
]
const photoType = ['.jpg', '.png', '.jpeg']
const afterPhotoType = 'image/jpeg'

const getPhotoBase64 = function (item) {
    return new Promise(function (resolve, reject) {
        let file = item.target.files[0]
        if (!item || !window.FileReader) return
        let reader = new FileReader()
        let fileName = item.target.value
        let sizeList = photoZoomout
        let typeList = photoType
        let afterType = afterPhotoType
        try {
            let seat = fileName.substring(fileName.lastIndexOf('.')).toLowerCase()
            let typeCheck = false
            typeList.forEach(e => {
                if (e === seat) {
                    typeCheck = true
                }
            })
            if (!typeCheck) {
                item.target.value = ''
                reject(new Error('只能上传图片文件！'))
            }
            let size
            let fileSize = Math.round(file.size / (1024 * 1024))
            if (fileSize < 2) {
                size = sizeList[0]
            } else if (fileSize >= 2 && fileSize < 5) {
                size = sizeList[1]
            } else if (fileSize >= 5 && fileSize < 10) {
                size = sizeList[2]
            } else {
                // 清空所选择文件路径
                item.target.value = ''
                reject(new Error('图片大小超过10M！上传失败！'))
            }
            let img = new Image()
            reader.onload = function (e) {
                // 文件加载成功后去转成Img对象，为了拿到图片的原始宽高
                img.src = e.target.result
                img.onload = function () {
                    // 创建画布canvas
                    let canvas = document.createElement('canvas')
                    let content = canvas.getContext('2d')
                    // 设置画布的宽高
                    canvas.width = img.width * size // 需要压缩到的图片宽度
                    canvas.height = img.height * size
                    // 将图片画在画布上
                    content.drawImage(img, 0, 0, canvas.width, canvas.height)
                    let fileBase64 = canvas.toDataURL(afterType, 0.92)
                    // 清空input的value值
                    e.target.value = ''
                    resolve(fileBase64)
                }
            }
            reader.readAsDataURL(file)
        } catch (e) {
            // ignore
            console.error(e)
            reject(e)
        }
    });
}


const utils = {
    getPhotoBase64
}
export default utils

